package com.dingreading.cloud.soms.service.impl;

import com.dingreading.cloud.common.util.NepUtil;
import com.dingreading.cloud.soms.entity.StoreProjectCycleConfig;
import com.dingreading.cloud.soms.entity.table.StoreProjectCycleConfigTableDef;
import com.dingreading.cloud.soms.mapper.StoreProjectCycleConfigMapper;
import com.dingreading.cloud.soms.service.StoreProjectCycleConfigService;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.update.UpdateChain;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2024-09-11
 */
@Service
public class StoreProjectCycleConfigServiceImpl extends BaseServiceImpl<StoreProjectCycleConfigMapper, StoreProjectCycleConfig, StoreProjectCycleConfigTableDef> implements StoreProjectCycleConfigService {

    @Override
    protected StoreProjectCycleConfigTableDef getTable() {
        return StoreProjectCycleConfigTableDef.storeProjectCycleConfig;
    }

    @Override
    public StoreProjectCycleConfig getByStoreUidAndProjectUidAndCycleUid(String storeUid, String projectUid, String cycleUid) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.storeUid.eq(storeUid));
        if (StringUtils.isNotBlank(projectUid))
            condition.and(table.projectUid.eq(projectUid));
        condition.and(table.cycleUid.eq(cycleUid));

        return getMapper().selectOneByCondition(condition);
    }

    @Override
    public boolean updateInfo(
            String storeUid, String projectUid, String cycleUid, String cycleConfigUid,
            Double totalAmount, Double unitAmount, Integer enabled, String staffUid, String staffName
    ) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.storeUid.eq(storeUid));
        if (StringUtils.isNotBlank(projectUid))
            condition.and(table.projectUid.eq(projectUid));
        condition.and(table.cycleUid.eq(cycleUid))
                .and(table.uid.eq(cycleConfigUid));

        UpdateChain<StoreProjectCycleConfig> updateChain = UpdateChain.of(StoreProjectCycleConfig.class);
        if (totalAmount != null)
            updateChain.set(table.totalAmount, totalAmount);
        if (unitAmount != null)
            updateChain.set(table.unitAmount, unitAmount);
        if (enabled != null)
            updateChain.set(table.enabled, enabled);

        return updateChain
                .set(table.lastStaffUid, NepUtil.nullToZero(staffUid))
                .set(table.lastStaffName, NepUtil.nullToZero(staffName))
                .where(condition)
                .update();
    }

    @Override
    public void deleteByCycleUid(String storeUid, String cycleUid) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.storeUid.eq(storeUid))
                .and(table.cycleUid.eq(cycleUid));

        getMapper().deleteByCondition(condition);
    }

}
